import { defineStore } from "pinia";
import { ref } from "vue";

export const useThemeStore = defineStore("theme", ()=>{
  const isDark = ref(false)
  
  function changeTheme(){
    isDark.value = !isDark.value
    if (isDark.value) {
      document.documentElement.classList.add('dark-mode');
    } else {
      document.documentElement.classList.remove('dark-mode');
    }
  }

  function setTheme(theme){
    isDark.value = theme === 'dark'
    document.documentElement.classList.toggle('dark-mode', isDark.value)
  }

  function initTheme() {
    // pinia持久化插件默认是以JSON格式存在本地，使用前需要转换数据类型
    const savedTheme = JSON.parse(localStorage.getItem('pinia-theme'));
    const theme = savedTheme || { isDark: false };
    if (theme.isDark) {
      isDark.value = true;
      document.documentElement.classList.add('dark-mode');
    }
  }

  return{
    isDark,changeTheme,initTheme,setTheme
  }
},{
  persist: true
})